<template>
  <div class="app-container">
    <!-- Header Section -->
    <header class="header">
      <img src="https://wx2.sinaimg.cn/mw690/d315af46ly1hnn5btbjr5j20j60j7mzv.jpg" alt="Logo" class="logo" />
      <div class="title-wrapper">
        <h1>果园农事小机器人</h1>
        <p>您的智能农业助手</p>
      </div>
      <transition name="fade-button">
        <button v-if="showClearButton" @click="clearChatHistory" class="clear-history-button">清空聊天记录</button>
      </transition>
    </header>

    <!-- Chat Container -->
    <div class="chat-container">
      <div class="chat-history" ref="chatHistory">
        <transition-group name="message-slide" tag="div">
          <div v-for="(message, index) in messages" :key="index" :class="['chat-message', message.type]">
            <div class="message-wrapper">
              <img :src="message.type === 'user' ? userAvatar : botAvatar" alt="Avatar" class="avatar" />
              <div class="message-content" v-html="parseMarkdown(message.text)"></div>
            </div>
            <div v-if="!message.finished && message.type === 'bot'" class="loading-indicator">...</div>
          </div>
        </transition-group>
      </div>
      <footer class="chat-input">
        <el-input v-model="userInput" placeholder="输入问题以获取帮助..." @keyup.enter.native="sendMessage">
          <template #append>
            <el-button icon="el-icon-s-promotion" @click="sendMessage" circle></el-button>
          </template>
        </el-input>
      </footer>
    </div>

    <!-- Notification for chat history cleared -->
    <transition name="notification">
      <div v-if="showNotification" class="notification">
        聊天记录已成功清空。
      </div>
    </transition>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userInput: '',
      messages: [], // 初始化为空数组，因为我们将从 localStorage 加载数据
      userAvatar: 'https://wx2.sinaimg.cn/mw690/d315af46ly1hnn5btbjr5j20j60j7mzv.jpg',
      botAvatar: 'https://wx2.sinaimg.cn/mw690/d315af46ly1hnn5btbjr5j20j60j7mzv.jpg',
      loadingTimeout: null,
      showClearButton: true, // 控制清除按钮的显示状态
      showNotification: false, // 控制通知的显示状态
      sessionId: '', // 新增属性用于存储会话ID
    };
  },
  mounted() {
    // 尝试从 localStorage 加载 sessionId 和 messages
    this.sessionId = localStorage.getItem('chatSessionId') || this.generateUUID();
    this.loadMessagesFromLocalStorage();
    this.scrollToBottom();

    // 如果没有加载到任何消息，添加默认的欢迎信息
    if (this.messages.length === 0) {
      this.messages.push({
        text: '<strong>您好！</strong><br>我是果园农事小机器人，有什么问题我可以帮助您解答吗？',
        type: 'bot',
        finished: true
      });
      this.saveMessagesToLocalStorage();
    }
  },
  methods: {
    generateUUID() {
      // 使用简单的方式生成 UUID
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      });
    },
    sendMessage() {
      if (this.userInput.trim()) {
        this.messages.push({ text: this.userInput, type: 'user', finished: true });
        this.userInput = '';

        const botMessage = { text: '', type: 'bot', finished: false };
        this.messages.push(botMessage);

        // const eventSource = new EventSource(`http://localhost:8081/ai/generateStream?message=${encodeURIComponent(this.messages[this.messages.length - 2].text)}`);

        const eventSource = new EventSource(`http://localhost:8081/ai/generateStream?message=${encodeURIComponent(this.messages[this.messages.length - 2].text)}&sessionId=${this.sessionId}`);

        eventSource.onmessage = (event) => {
          try {
            const response = JSON.parse(event.data);

            if (response.text !== undefined) {
              // 更新聊天记录中的文本内容
              this.$set(botMessage, 'text', botMessage.text + this.formatText(response.text));
              this.scrollToBottom();
            }

            if (response.finished === true) {
              // 如果收到结束标志，则标记为已完成
              this.$set(botMessage, 'finished', true);
              this.scrollToBottom();
            }

            // 每次接收到服务器响应后保存消息
            this.saveMessagesToLocalStorage();

          } catch (error) {
            console.error('Error processing server response:', error);
          }
        };

        eventSource.onerror = () => {
          eventSource.close();
          if (!botMessage.finished) {
            this.$set(botMessage, 'text', botMessage.text + '<br>很抱歉，我遇到了一些问题，未能获取您的答案。请稍后再试。');
            this.$set(botMessage, 'finished', true);
            this.scrollToBottom();
            // 在错误发生后也保存消息
            this.saveMessagesToLocalStorage();
          }
        };
        this.saveMessagesToLocalStorage();
      }
    },
    scrollToBottom() {
      const chatHistory = this.$refs.chatHistory;
      if (chatHistory) {
        chatHistory.scrollTop = chatHistory.scrollHeight;
      }
    },
    formatText(text) {
      return text.replace(/\n/g, '<br>');
    },
    parseMarkdown(text) {
      // 将 ### 转换为 <h3>
      text = text.replace(/^###\s+(.*)$/gm, '<h3>$1</h3>');
      // 将 **加粗文本** 转换为 <strong>加粗文本</strong>
      text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
      // 其他 Markdown 规则可以根据需要添加
      return text;
    },
    loadMessagesFromLocalStorage() {
      const storedMessages = localStorage.getItem('chatMessages');
      if (storedMessages) {
        try {
          this.messages = JSON.parse(storedMessages);
          this.sessionId = localStorage.getItem('chatSessionId') || this.generateUUID(); // 尝试恢复 sessionId
        } catch (e) {
          console.error('Failed to parse chat messages from localStorage:', e);
        }
      }
    },
    saveMessagesToLocalStorage() {
      try {
        localStorage.setItem('chatMessages', JSON.stringify(this.messages));
        localStorage.setItem('chatSessionId', this.sessionId); // 保存 sessionId 到 localStorage
      } catch (e) {
        console.error('Failed to save chat messages or sessionId to localStorage:', e);
      }
    },
    clearChatHistory() {
      // 清空组件内的消息列表
      this.messages = [];
      // 清空 localStorage 中的消息记录和 sessionId
      localStorage.removeItem('chatMessages');
      localStorage.removeItem('chatSessionId');
      this.sessionId = this.generateUUID(); // 生成新的 sessionId

      // 显示通知并设置定时器来自动隐藏它
      this.showNotification = true;
      setTimeout(() => {
        this.showNotification = false;
      }, 1500); // 3秒后隐藏通知

      // 自动隐藏清除按钮
      this.showClearButton = false;
      setTimeout(() => {
        this.showClearButton = true;
      }, 5000); // 5秒后重新显示按钮
    }
  }
};
</script>


<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css');

.app-container {
  font-family: 'Roboto', sans-serif;
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: linear-gradient(135deg, #e8f0fe 0%, #bbdefb 100%);
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 40px;
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 1;
}

/* 改进后的清除聊天记录按钮 */
.clear-history-button {
  padding: 10px 20px;
  font-size: 16px;
  color: #fff;
  background-color: #f56c6c;
  border: none;
  border-radius: 25px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.clear-history-button:hover {
  background-color: #c82333;
}

.fade-button-enter-active, .fade-button-leave-active {
  transition: opacity 0.5s;
}
.fade-button-enter, .fade-button-leave-to /* .fade-button-leave-active below version 2.1.8 */ {
  opacity: 0;
}

/* 标题样式优化 */
.title-wrapper h1 {
  font-size: 1.75rem;
  font-weight: 700;
  color: #333;
  margin: 0;
}

.title-wrapper p {
  font-size: 1rem;
  color: #666;
  margin: 0;
}

/* 提示框样式 */
.notification {
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding: 15px 30px;
  font-size: 1rem;
  color: #fff;
  background-color: #28a745;
  border-radius: 25px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  animation: slideIn 0.5s forwards;
}

.notification-enter-active, .notification-leave-active {
  transition: opacity 0.5s, transform 0.5s;
}
.notification-enter, .notification-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

/* 动画定义 */
@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 现有的其他样式保持不变 */

.logo {
  width: 50px;
  height: auto;
  border-radius: 50%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #fff;
  border-top-left-radius: 20px;
  border-top-right-radius: 20px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.chat-history {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f5f5f5;
  border-bottom-left-radius: 20px;
  border-bottom-right-radius: 20px;
}

.message-slide-enter-active,
.message-slide-leave-active {
  transition: all 0.3s ease;
}

.message-slide-enter-from,
.message-slide-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

.chat-message {
  max-width: 100%;
  display: flex;
  align-items: flex-start;
  margin: 10px 0;
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: scale(0.9);
  }

  to {
    opacity: 1;
    transform: scale(1);
  }
}

.message-wrapper {
  display: flex;
  align-items: flex-start;
  flex-grow: 1;
}

.chat-message.bot .message-wrapper {
  justify-content: flex-start;
  margin-left: 0;
}

.chat-message.user .message-wrapper {
  justify-content: flex-end;
  margin-right: 0;
  flex-direction: row-reverse;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin: 0 10px;
}

.message-content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 20px;
  position: relative;
  word-break: break-word;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chat-message.bot .message-content {
  background-color: #ffffff;
  color: #232323;
  margin-left: 10px;
}

.chat-message.user {
  justify-content: flex-end;
}

.chat-message.user .avatar {
  margin-left: 10px;
  margin-right: 0;
}

.chat-message.user .message-content {
  background-color: #95ec69;
  color: #232323;
  margin-right: 0;
  margin-left: auto;
  max-width: calc(100% - 60px);
}

.chat-input {
  display: flex;
  padding: 10px 20px;
  background-color: #ffffff;
  border-top: none;
}

.el-input {
  flex: 1;
  margin-right: 10px;
}

.el-input input {
  border-radius: 20px;
  padding-left: 20px;
}

.el-input-group__append button {
  padding: 0 15px;
  font-size: 1.2rem;
  color: #ffffff;
  background-color: #007bff;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.el-input-group__append button:hover {
  background-color: #0056b3;
}

/* Responsive Design */
@media (max-width: 768px) {
  .chat-message {
    max-width: 90%;
  }

  .header {
    padding: 20px;
  }

  .logo {
    width: 40px;
  }
}
</style>